package com.appspot.modutajataja;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MoaGame extends Activity {
	
	String gameName = "moaGame";						// 게임 이름
	int arrImageMe[] = { 0, 0, 0 }; 								// 내가위바위보이미지
	int arrImageCom[] = { 0, 0, 0 }; 							// 컴퓨터 가위바위보이미지
	int result; 																	// win-draw-lose
	int myScore = 0; 														// 내스코어 담기
	long startTime = 0L; 												// 타이머의 스타팅시간
	int mychoice_num1; 												// 내첫번째랜덤선택값
	int mychoice_num2; 												// 내두번째랜덤선택값
	int comchoice_num1; 											// 컴퓨터첫번째랜덤선택값
	int comchoice_num2; 											// 컴퓨터 두번째 랜덤선택값
	int mychoice_final_num; 										// 내 마지막 랜덤선택값
	int comchoice_final_num; 									// 컴퓨터 마지막 랜덤선택값
	int com_char; 															// 컴퓨터 초이스성향
	
	Handler mHandler = new Handler(); 					// 핸들러
	Handler lHandler = new Handler();					// 핸들러
	Handler nHandler = new Handler(); 					// 핸들러
	Handler oHandler = new Handler(); 					// 핸들러
	Handler pHandler = new Handler(); 					// 핸들러
	
	Runnable mUpdateTimeTask;							// 시간 러너블
	Runnable shuffleTask;											// 랜덤 러너블
	Runnable musicTask;											// 음악 러너블
	Runnable winTask;												// 승리 러너블
	Runnable drawTask;												// 무승부 러너블
	Runnable loseTask;												// 패배 러너블
	
	TextView timer; 														// 타이머레이아웃
	ImageView mychoice_final; 								// 나의 마지막 선택
	ImageView comchoice_final; 								// 컴퓨터의 마지막선택
	ImageView mychoice1; 										// 내 첫번째 랜덤선택
	ImageView mychoice2; 										// 내 두번째 랜덤선택
	ImageView comchoice1;										// 컴퓨터 첫번째 랜덤선택
	ImageView comchoice2;										// 컴퓨터 두번째 랜덤선택

	MediaPlayer mediaPlayer;									// 게임 배경 음악
	MediaPlayer Start_Player;									// 가위바위보 스타트 음성
	MediaPlayer win_Player;										// 승리시 음성
	MediaPlayer draw_Player;									// 비길시 음성
	MediaPlayer lose_Player;									// 패배시 음성
	MediaPlayer gameSoundReadygo;					// 게임효과음 실행 변수
	MediaPlayer gameSoundTok; 							// 게임효과음 실행 변수

	ImageView win;														// 승리 이미지
	ImageView lose;														// 패배 이미지
	ImageView draw;													// 무승부 이미지

	ImageView pLogo1;												// 승리시 경품 이미지 1
	ImageView pLogo2;												// 승리시 경품 이미지 2
	ImageView pLogo3;												// 승리시 경품 이미지 3
	ImageView pLogo4;												// 승리시 경품 이미지 4
	ImageView pLogo5;												// 승리시 경품 이미지 5
	
	ImageView gameReady;										// 게임 준비 이미지 뷰
	ImageView gameStart;											// 게임 시작 이미지 뷰
	int imageIndex;														// 게임 준비/시작 이미지 변경을 위한 인덱스
	
	Timer timerCard = new Timer(); 							// 카드 초기세팅을 위한 타이머
	int[] pLogo = new int[] { R.id.pLogo1, R.id.pLogo2, R.id.pLogo3, R.id.pLogo4, R.id.pLogo5 };
	
	private String userId;											// 사용자 유저 ID
	String outTime;
	long time;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.moa_game);

		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		
		TextView myName = (TextView) findViewById(R.id.myName);
		userId = getIntent().getStringExtra("userId");
		myName.setText(userId);

		win = (ImageView) findViewById(R.id.game_win);
		lose = (ImageView) findViewById(R.id.game_lose);
		draw = (ImageView) findViewById(R.id.game_draw);
		
		gameReady = (ImageView) findViewById(R.id.moa_game_ready);
		gameStart = (ImageView) findViewById(R.id.moa_game_go);

		arrImageMe[0] = R.drawable.scissors_left;
		arrImageMe[1] = R.drawable.rock_left;
		arrImageMe[2] = R.drawable.paper_left;
		
		arrImageCom[0] = R.drawable.scissors_right;
		arrImageCom[1] = R.drawable.rock_right;
		arrImageCom[2] = R.drawable.paper_right;
		
		// 파이널초이스 온클릭
		mychoice_final = (ImageView) findViewById(R.id.mychoice_final);
		comchoice_final = (ImageView) findViewById(R.id.comchoice_final);

		mychoice1 = (ImageView) findViewById(R.id.mychoice1);
		mychoice2 = (ImageView) findViewById(R.id.mychoice2);
		comchoice1 = (ImageView) findViewById(R.id.comchoice1);
		comchoice2 = (ImageView) findViewById(R.id.comchoice2);

		mychoice1.setOnClickListener(MyButtonListener);
		mychoice2.setOnClickListener(MyButtonListener);
			
		// 타이머 셋
		timer = (TextView) findViewById(R.id.time_count);
		timer.setTypeface(Typeface.createFromAsset(getAssets(), "fonts/cartoonist.ttf"));
		
		final Handler handler = new Handler();
		TimerTask task = new TimerTask() {
			@Override
			public void run() {
				handler.post(new Runnable() {
					@Override
					public void run() {	
						if(imageIndex==0) {
							gameReady.setVisibility(View.VISIBLE);
							gameReady.bringToFront();						//레이아웃 우선 순위 설정
							gameSoundReadygo.start();
							imageIndex=1;
						} else if(imageIndex==1) {
							gameReady.setVisibility(View.INVISIBLE);
							gameStart.setVisibility(View.VISIBLE);
							gameStart.bringToFront();
							imageIndex=2;
						} else if(imageIndex==2) {
							gameStart.setVisibility(View.INVISIBLE);							
							// 타이머 시작값 세팅및 타이머 실행
							startTime = System.currentTimeMillis();
							mUpdateTimeTask.run();
							// 셔플실행 & 음악실행 - 가위바위보
							shuffleTask.run();
							// 뮤직컨트롤
							musicControl();
							timerCard.cancel();
						}
					}
				});
			}
		};
		timerCard.schedule(task, 1000, 1000);

		// 뮤직러너블 - 음악종료와 동시에 셔플중지 & 카드랜덤선택
		musicTask = new Runnable() {
			@Override
			public void run() {
				lHandler.removeCallbacks(shuffleTask);
				start();
				mychoice1.setClickable(true);
				mychoice2.setClickable(true);
				lHandler.postDelayed(null, 500);
			}
		};

		// 타이머러너블
		mUpdateTimeTask = new Runnable() {
			@Override
			public void run() {
				updateTime();
			}
		};

		// 셔플러너블
		shuffleTask = new Runnable() {
			@Override
			public void run() {
				int i = new Random().nextInt(3);
				int j = new Random().nextInt(3);
				mychoice1.setImageResource(arrImageMe[i]);
				mychoice2.setImageResource(arrImageMe[i]);
				comchoice1.setImageResource(arrImageCom[j]);
				comchoice2.setImageResource(arrImageCom[j]);
				lHandler.postDelayed(shuffleTask, 70);
			}
		};

		// win러너블
		winTask = new Runnable() {
			@Override
			public void run() {
				win_Player.stop();
				restart("win");
			}
		};
		
		// draw러너블
		drawTask = new Runnable() {
			@Override
			public void run() {
				draw_Player.stop();
				restart("draw");
			}
		};
		
		// lose러너블
		loseTask = new Runnable() {
			@Override
			public void run() {
				lose_Player.stop();
				restart("lose");
			}
		};
	} // oncreate

	public void musicControl() {
		mychoice1.setClickable(false);
		mychoice2.setClickable(false);
		Start_Player = MediaPlayer.create(MoaGame.this, R.raw.kbb);
		Start_Player.setLooping(false);
		Start_Player.start();
		nHandler.postDelayed(musicTask, 1500);
	}

	// 스타트로직 - 4개버튼 넘버세팅, 컴퓨터성향세팅,
	public void start() {
		// 4개 랜덤생성
		mychoice_num1 = new Random().nextInt(3);
		mychoice_num2 = new Random().nextInt(3);

		while (true) {
			if (mychoice_num1 == mychoice_num2) {
				mychoice_num2 = new Random().nextInt(3);
			} else {
				break;
			}
		}

		comchoice_num1 = new Random().nextInt(3);

		while (true) {
			comchoice_num2 = new Random().nextInt(3);
			if (comchoice_num1 == comchoice_num2) {
				comchoice_num2 = new Random().nextInt(3);
			} else {
				break;
			}
		}
		// 컴퓨터 성향세팅 (0=pessive, 1=aggressive)
		com_char = new Random().nextInt(2);

		// 버튼에 그림그리기
		Display();
	}

	// 디스플레이로직
	void Display() {
		mychoice1.setImageResource(arrImageMe[mychoice_num1]);
		mychoice2.setImageResource(arrImageMe[mychoice_num2]);
		comchoice1.setImageResource(arrImageCom[comchoice_num1]);
		comchoice2.setImageResource(arrImageCom[comchoice_num2]);
		mychoice_final.setImageResource(R.drawable.questionmark);
		comchoice_final.setImageResource(R.drawable.questionmark);
	}

	// 타이머 로직
	public void updateTime() {
		time = System.currentTimeMillis() - startTime;
		outTime = String.format("%02d : %02d : %02d", time/1000/60, (time/1000)%60, (time%1000)/10);
		timer.setText(outTime);		
		mHandler.postDelayed(mUpdateTimeTask, 10);		
	}// updateTime

	// 리스타트 메소드
	public void restart(String result) {
		lose.setClickable(false);
		draw.setClickable(false);
		mychoice1.setVisibility(View.VISIBLE);
		mychoice2.setVisibility(View.VISIBLE);
		mychoice1.setEnabled(true);
		mychoice2.setEnabled(true);
		comchoice1.setVisibility(View.VISIBLE);
		comchoice2.setVisibility(View.VISIBLE);

		if(result == "lose" || result == "draw") {						
			lose.setVisibility(View.INVISIBLE);
			draw.setVisibility(View.INVISIBLE);
		} else if(result == "win") {
			// 하나씩 광고 보이는 로직
			ImageView imageView = null;
			for (int i = 0; i < myScore; i++) {
				imageView = (ImageView)findViewById(pLogo[i]);
				imageView.setVisibility(View.VISIBLE);
			}
			win.setVisibility(View.INVISIBLE);
		}
		// 기본로직
		mychoice1.setClickable(true);
		mychoice2.setClickable(true);
		mychoice_final.setImageResource(R.drawable.questionmark);
		comchoice_final.setImageResource(R.drawable.questionmark);
		shuffleTask.run();
		musicControl();
	}

	// 주사위 선택 및 파이널 선택 리스너
	Button.OnClickListener MyButtonListener = new Button.OnClickListener() {
		public void onClick(View v) {
			lose.setClickable(true);
			draw.setClickable(true);

			// 파이널 정해주기
			if (v.getId() == R.id.mychoice1) {
				mychoice1.setVisibility(View.INVISIBLE);
				mychoice2.setEnabled(false);
				mychoice_final.setImageResource(arrImageMe[mychoice_num1]);
				mychoice_final_num = mychoice_num1;
			} else if (v.getId() == R.id.mychoice2) {
				mychoice2.setVisibility(View.INVISIBLE);
				mychoice1.setEnabled(false);
				mychoice_final.setImageResource(arrImageMe[mychoice_num2]);
				mychoice_final_num = mychoice_num2;
			}

			// 컴퓨터측 가져오기
			if ((comchoice_num1 == mychoice_num1 || comchoice_num1 == mychoice_num2)
					&& (comchoice_num2 == mychoice_num1 || comchoice_num2 == mychoice_num2)) {
				if (comchoice_num1 - comchoice_num2 == 1
						|| comchoice_num1 - comchoice_num2 == -2) {
					comchoice_final
							.setImageResource(arrImageCom[comchoice_num1]);
					comchoice_final_num = comchoice_num1;
					comchoice1.setVisibility(4);
				} else {
					comchoice_final
							.setImageResource(arrImageCom[comchoice_num2]);
					comchoice_final_num = comchoice_num2;
					comchoice2.setVisibility(4);
				}
			}

			else if ((comchoice_num1 == mychoice_num1 || comchoice_num1 == mychoice_num2)
					|| (comchoice_num2 == mychoice_num1 || comchoice_num2 == mychoice_num2)) {

				// conservative = 양쪽에 같은거 냄 = draw확률상승, 승패확률저하
				if (com_char == 0
						&& (comchoice_num1 == mychoice_num1 || comchoice_num1 == mychoice_num2)) {
					comchoice_final
							.setImageResource(arrImageCom[comchoice_num1]);
					comchoice_final_num = comchoice_num1;
					comchoice1.setVisibility(4);
				}
				if (com_char == 0
						&& (comchoice_num2 == mychoice_num1 || comchoice_num2 == mychoice_num2)) {
					comchoice_final
							.setImageResource(arrImageCom[comchoice_num2]);
					comchoice_final_num = comchoice_num2;
					comchoice2.setVisibility(4);
				}

				// aggressive = 양쪽에 다른거 냄 = draw확률저하, 승패확률상승
				if (com_char == 1
						&& (comchoice_num1 == mychoice_num1 || comchoice_num1 == mychoice_num2)) {
					comchoice_final
							.setImageResource(arrImageCom[comchoice_num2]);
					comchoice_final_num = comchoice_num2;
					comchoice2.setVisibility(4);
				}
				if (com_char == 1
						&& (comchoice_num2 == mychoice_num1 || comchoice_num2 == mychoice_num2)) {
					comchoice_final
							.setImageResource(arrImageCom[comchoice_num1]);
					comchoice_final_num = comchoice_num1;
					comchoice1.setVisibility(4);
				}
			}
			PanJung(mychoice_final_num, comchoice_final_num);
		}
	}; // 마이버튼 리스너

	// 판정로직
	void PanJung(int mychoice_final_num, int comchoice_final_num) {
		
		if (mychoice_final_num == comchoice_final_num) {
			result = 0;
		} // 비겼다
		else if (mychoice_final_num - comchoice_final_num == 1
				|| mychoice_final_num - comchoice_final_num == -2) {
			result = 1;
		} // 이겼다
		else {
			result = 2;
		} // 졌다

		// 이겼으면 하나올려
		if (result == 1) {
			myScore++;
			win.setVisibility(View.VISIBLE);			
			win_Player = MediaPlayer.create(MoaGame.this, R.raw.win);
			win_Player.setLooping(false);
			win_Player.start();
			
			if (myScore < 5) {
				// 클릭리스너 disable
				mychoice1.setClickable(false);
				mychoice2.setClickable(false);
				oHandler.postDelayed(winTask, 1000);
			} else if (myScore == 5) {
				// 타이머 중지로직
				mHandler.removeCallbacks(mUpdateTimeTask);
				new Handler().postDelayed(new Runnable() {
					public void run() {
						Bundle extras = new Bundle();
						extras.putLong("result_time", time);						
						extras.putString("gameName", gameName);
						extras.putString("userId", userId);						
						startActivity((new Intent(MoaGame.this, GameScore.class).putExtras(extras)));					
					}
				}, 2000);				
			}
			
		}

		if (result == 2) {
			lose.setVisibility(View.VISIBLE);
			lose_Player = MediaPlayer.create(MoaGame.this, R.raw.lose);
			lose_Player.setLooping(false);
			lose_Player.start();
			oHandler.postDelayed(loseTask, 1000);
		}

		if (result == 0) {
			draw.setVisibility(View.VISIBLE);
			draw_Player = MediaPlayer.create(MoaGame.this, R.raw.draw);
			draw_Player.setLooping(false);
			draw_Player.start();
			oHandler.postDelayed(drawTask, 1000);
		}		

	} // 판정메소드

	public void backmusic() {
		mediaPlayer = MediaPlayer.create(this, R.raw.moa_game);
		mediaPlayer.setLooping(true);
		mediaPlayer.start();
	}

	@Override
	protected void onResume() {
		super.onResume();
		gameSoundReadygo = MediaPlayer.create(this, R.raw.readygo);
		backmusic();
	}

	@Override
	protected void onPause() {
		super.onPause();
		Start_Player.stop();
		mediaPlayer.stop();
		finish();
	}

	@Override
	public void onBackPressed() { ; }
};